<template>
  <div class="article-editor">
    <div class="back" @click="back">返回</div>
    <el-button v-if="!isEidt" type="primary" @click="submitForm(0)">保存</el-button>
    <el-button v-if="!isEidt" type="primary" @click="submitForm(1)">发布</el-button>
    <el-button v-if="isEidt" type="primary" @click="submitForm()">更新</el-button>
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" autocomplete="off" placeholder="请输入标题"></el-input>
      </el-form-item>

      <el-form-item label="标签" prop="tag_id">
        <el-select
          v-if="tagList.length > 0"
          v-model="form.tag_id"
          placeholder="请选择标签"
          @change="setTagId"
        >
          <el-option
            v-for="item in tagList"
            :key="item.tag_id"
            :label="item.tag_name"
            :value="item.tag_id"
            :content="item.tag_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input v-model="form.type" autocomplete="off" placeholder="请输入类型,此处用于分类自定义业务"></el-input>
      </el-form-item>
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="form.keyword" autocomplete="off" placeholder="多个关键字用空格隔开"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="2"
          autocomplete="off"
          placeholder="图片类型的文章,此处放入缩略图的url"
        ></el-input>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker
          v-model="createTime"
          @change="handleChangeTime"
          type="datetime"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <div class="md-editor-wrap" v-if="isMDEditor">
      <mavon-editor
        ref="md"
        @imgAdd="$imgAdd"
        v-model="content"
        @imgDel="$imgDel"
        :codeStyle="'monokai'"
      ></mavon-editor>
    </div>
    <div class="html-editor-wrap" v-else>
      <div class="html-editor">
        <HTMLEditor
          style="min-height: 200px; margin-bottom: 20px;"
          v-model="content"
          @text-change="textChangeHandler"
          @selection-change="selectionChangeHandler"
          @editor-change="editorChangeHandler"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
const { mapActions, mapState } = createNamespacedHelpers("admin");
import HTMLEditor from "@c/HTMLEditor";
export default {
  components: {
    HTMLEditor
  },
  props: {},
  data() {
    return {
      content: "",
      isView: true,
      isMDEditor: true,

      formLabelWidth: "120px",
      form: {
        title: "",
        description: "",
        tag_id: null,
        tag_name: null,
        type: "",
        keyword: ""
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        description: [
          { required: true, message: "请输入简介", trigger: "blur" }
        ],
        tag_id: [{ required: true, message: "请选择标签", trigger: "blur" }],
        type: [{ required: true, message: "请输入类型", trigger: "blur" }]
      },

      createTime: "",

      tagList: [],

      // 编辑
      articleId: "",
      isEidt: false
    };
  },
  computed: {
    ...mapState(["userInfo"])
  },
  watch: {
    $route: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val.query.id && val.query.isUse === "edit") {
          this.articleId = val.query.id;
          this.isEidt = true;
          this.fetchArticleDetail();
        }
      }
    },
    isMDEditor(val) {
      if (val) {
        const dom = document.querySelector(".ql-toolbar");
        dom && dom.remove();
      }
    }
  },
  mounted() {
    this.fetchTagList();
  },
  methods: {
    ...mapActions([
      "addArticle",
      "updateArticle",
      "getTaglist",
      "getArticleDetail",
      "singleUpload"
    ]),
    fetchArticleDetail() {
      this.getArticleDetail(this.articleId).then(res => {
        this.form.title = res.title;
        this.form.description = res.description;
        this.form.tag_id = res.tag_id;
        this.form.tag_name = res.tag_name;
        this.form.keyword = res.keyword;
        this.form.type = res.type;
        this.content = res.content;
      });
    },
    fetchTagList() {
      this.getTaglist().then(res => {
        this.tagList = res.list;
      });
    },
    $imgAdd(pos, $file) {
      if (!this.userInfo.username) return;
      // 将图片上传到服务器.
      const formdata = new FormData();
      formdata.set("name", $file.name);
      formdata.set("username", this.userInfo.username);
      formdata.set("file", $file);
      this.singleUpload(formdata).then(res => {
        res.url && this.$refs.md.$img2Url(pos, res.url);
      });
    },
    $imgDel() {},

    submitForm(status) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.isEidt) {
            this.handleUpdate();
          } else {
            this.handleAddSubmit(status);
          }
        } else {
          return false;
        }
      });
    },
    handleAddSubmit(status) {
      const params = {
        title: this.form.title,
        status,
        description: this.form.description,
        content: this.content,
        tag_id: this.form.tag_id,
        tag_name: this.form.tag_name,
        keyword: this.form.keyword,
        type: this.form.type,
        user_id: this.userInfo.user_id || 1,
        username: this.userInfo.username || "",
        real_name: this.userInfo.real_name || ""
      };
      if (this.create_time) {
        params.create_time = this.create_time;
      }
      this.addArticle(params).then(() => {
        this.$message({
          type: "message",
          message: "提交成功"
        });
        this.back();
      });
    },

    handleUpdate() {
      const params = {
        title: this.form.title,
        description: this.form.description,
        content: this.content,
        tag_id: this.form.tag_id,
        tag_name: this.form.tag_name,
        keyword: this.form.keyword,
        type: this.form.type,
        article_id: this.articleId
      };
      if (this.create_time) {
        params.create_time = this.create_time;
      }
      this.updateArticle(params).then(() => {
        this.$message({
          type: "message",
          message: "更新成功"
        });
        this.back();
      });
    },

    setTagId(val) {
      const tagIndex = this.tagList.findIndex(i => i.tag_id === val);
      this.form.tag_name = this.tagList[tagIndex].tag_name;
      this.form.tag_id = val;
    },
    handleChangeTime(val) {
      const createTime = new Date(val).getTime();
      this.create_time = createTime;
    },
    back() {
      this.$router.push({
        name: "admin-article"
      });
    },

    // html editor

    textChangeHandler() {},
    selectionChangeHandler() {},
    editorChangeHandler() {}
  }
};
</script>

<style lang="scss" scoped>
.article-editor {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: auto;
  .back {
    position: absolute;
    top: 5px;
    left: 24px;
  }
  .el-form {
    width: 500px;
    display: flex;
    flex-flow: column;
    align-items: flex-start;
    .el-form-item {
      width: 100%;
      .el-select {
        width: 100%;
      }
    }
  }

  .html-editor-wrap {
  }
}
</style>
